exports.plugin = {
  name: 'outlinesModel',
  register: (server) => {
    const { mongoose } = server;
    const schema = mongoose.Schema({
      outlinename: String,
      pid: {
        type: String,
        default: 0,
      },
      ctime: {
        type: Date,
        default: Date.now,
      },
    });

    schema.methods = {
      // 排序（交换两个同级节点的位置）
      async outlineSort({ firstId, secondId }) {
        const { ctime: firstCtime } = await this.model('outlines').findById(firstId);
        const { ctime: secondCtime } = await this.model('outlines').findOneAndUpdate({ _id: secondId }, { ctime: firstCtime });
        await this.model('outlines').findOneAndUpdate({ _id: firstId }, { ctime: secondCtime });
      },
      // 获取大纲
      getOutlines() {
        const result = this.model('outlines').find({}, { __v: 0 }).sort({ ctime: -1 });
        return result;
      },
      // 添加大纲
      addOutlines(data) {
        return this.model('outlines').create(data);
      },
      // 根据ID获取单个大纲信息
      getOutlineById(_id) {
        return this.model('outlines').findById(_id, { __v: 0 });
      },
      // 获取字节点
      getChildrenNodes(pid) {
        return this.model('outlines').find({ pid }, { __v: 0 });
      },
      // 根据ID删除大纲
      deleteOutlineById(_id) {
        return this.model('outlines').deleteOne({ _id });
      },
      // 根据ID更新大纲信息
      updateOutlineById(_id, data) {
        return this.model('outlines').updateOne({ _id }, data);
      },
      // 判断字段值是否存在
      isExist(field, value) {
        return this.model('outlines').findOne({ [field]: value });
      },
    };
    const Outlines = mongoose.model('outlines', schema);
    server.decorate('request', 'outlinesModel', new Outlines());
  },
};
